<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getbooks">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="books" highlight-current-row v-loading="listLoading" @selection-change="selsChange"@row-dblclick="handleRowDblClick" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
<!--      <el-table-column type="index" width="60">-->
<!--      </el-table-column>-->
      <el-table-column prop="book_id" label="" width="120" sortable>
      </el-table-column>
      <el-table-column prop="bookname" label="字典名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="bookno" label="字典编号" width="100" sortable>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <!-- elmentUi提供的按钮：size表示大小，type表示按钮颜色
        	scope.$index：当前行下标
        	scope.row：当前行对象
        -->
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
              <!--
          :disabled="this.sels.length===0" - 当选中的条数为0就禁用
          @click="batchRemove" - 单击事件调用batchRemove方法
        -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" ref="saveForm">
<!--        id: null,-->
<!--        //e.id,e.username,e.phone,e.email,e.age,e.state,e.department_id-->
<!--        bookname: '',-->
<!--        bookno: '',-->
        <el-table-column prop="book_id" label="ID" width="120" sortable>
        </el-table-column>
        <el-form-item label="字典名称" prop="username">
          <el-input v-model="saveForm.bookname" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="字典编号" prop="phone">
          <el-input v-model="saveForm.bookno" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交			</el-button>
      </div>
    </el-dialog>

    <!-- 对话框 -->
    <template>
      <!-- ... 其他代码 ... -->
      <el-dialog
          title="当前数据字典类型详情"
          :visible.sync="dialogVisible"
          width="30%"
          @close="handleDialogClose"
      >
        <tr>
          <td>
            序号
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          </td>
          <td>
            字典详细名称:
          </td>
        </tr>
        <table v-for="bookde in bookdes">
          <div v-if="bookde.dno==bookdename">
            <tr>
              <td>
                {{ bookde.did }}
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              </td>
              <td>
                {{ bookde.dname }}
              </td>
            </tr>
          </div>
        </table>
        <!-- 可以根据需要添加更多详情 -->
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </el-dialog>
      <!-- ... 其他代码 ... -->
    </template>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getbookListPage, removebook, batchRemovebook, editbook, savebook } from '../../api/api';

export default {
  data() {
    return {
      /*1.分页条*/
      pageSize: 5,
      currentPage: 1,
      totals: 0,
      /*2. 部门表格数据绑定*/
      books: [],
      managers: [],
      deptTree: [],
      bookdes:[],
      keyword: "",
      // saveFormRules: {		//验证规则
      //   sn: [
      //     {required: true, message: '请输入部门编号', trigger: 'blur'}
      //   ],
      //   name: [
      //     {required: true, message: '请输入部门名称', trigger: 'blur'}
      //   ]
      // },
      filters: {
        name: ''
      },
      saveLoading:false,
      listLoading: false,
      dialogVisible:false,
      sels: [],//列表选中列
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //新增界面数据
      //编辑界面数据
      saveForm: {
        id: null,
        //e.id,e.username,e.phone,e.email,e.age,e.state,e.department_id
        bookname: '',
        bookno: '',
      },
      saveFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      bookdename:'',

    }
  },
  methods: {
    //获取细节
    getbookdes(){
      this.$http.get("/bookde").then(res => {
        this.bookdes = res.data;
      })
    },
    //双击
    handleRowDblClick(row, column, event) {
      this.openDetailDialog(row.bookname);
      this.getbookdes();
    },
    openDetailDialog(rowData) {
      this.bookdename = rowData; // 把这行的type类型传给这个data 综的name
      this.dialogVisible = true;
    },


    /*1.当页数改变调用得方法*/
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getbooks();
    },
    /*2.查询分页数据得方法*/
    //获取部门列表111
    getbooks() {
      let para = {  //{currentPage:xxx,pageSize:xxxx}后端query
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      //页面一加载就显示加载框
      this.listLoading = true;
      this.$http.post("/book", para).then(result => {   //请求成功
        let {data, totals} = result.data
        this.books = data;
        this.totals = totals;
        this.listLoading = false; //关闭忙态框
      }).catch(result => {
        this.$message.error('系统繁忙，请稍后重试！！！');
      })

    },

    //获取部门经理 - 所有的员工
    getManagers(){
      this.$http.get("/book").then(res => {
        console.log(111);
        this.managers = res.data;
      })
    },

    //点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "编辑";
      this.saveForm = Object.assign({}, row);
      this.saveFormVisible = true;
    },

    //点击添加按钮弹出模态框
    handleAdd: function () {
          this.title = "添加";
          this.saveForm = {
            id: null,
            //e.id,e.username,e.phone,e.email,e.age,e.state,e.department_id
            bookname: '',
            bookno: '',
          };
          this.saveFormVisible = true;
        },

    //细节：如果是用对象回显【v-model="saveForm.manager"】，提交数据到后端是对部门经理的处理。如果是id不用管
    //对部门经理做处理:当选了部门经理然后点击x掉之后，提交的数据是一个''，后端无法接收
    //    paras.manager = paras.manager?paras.manager:null;

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗? 同时会删除数据字典明细 对应的品牌名字', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/book/" + row.book_id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            if ((this.totals - 1) % this.pageSize == 0) {
              //说明已经是在删除当前页得最后一条： 当前页减一之后在查询
              this.currentPage -= 1
            }
            this.getbooks();
          } else {
            this.$message.error("删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
        //确认框点击取消之后走这里
      });
    },
    //方法methods：
//获取部门树 - 无线级联
    getDeptTree(){
      this.$http.get("/book/deptTree").then(res => {
        this.deptTree = res.data;
      })
    },
    //编辑
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            editbook(para).then((res) => {
              this.editLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.getbooks();
            });
          });
        }
      });
    },
    //新增
    saveSubmit: function () {
      console.log(111)
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let paras = Object.assign({}, this.saveForm);

            //提交数据时上级部门数据格式做处理：
            let arr = paras.parent_id;
            if(arr && arr.length==0){//点击清理的时候，是[]
              paras.parent_id = null;
            }
            if(arr && arr.length>0){ //[1,13]
              paras.parent_id = arr[arr.length-1];
            }

            this.$http.put("/book",paras).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if(res.data.success){
                this.getbooks();
              }else{
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.$message.error("系统错误【400,404】");
            })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.book_id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        this.$http.patch("/book", ids).then(res => {
          //NProgress.start();
          let {success, message} = res.data;
          if (success) {
            this.$message({
              message: message,
              type: 'success'
            });
            if ((this.total - ids.length) % this.pageSize == 0) {
              this.currentPage -= 1;
            }
            this.getbooks()
          } else {
            this.$message({
              message: message,
              type: 'error'
            });
          }
          this.listLoading = false;
        }).catch(res => {
        })
      })

    },
  },
  mounted() {
    this.getbooks();
  }

}



</script>

<style scoped>

</style>